package com.ruyuan.rapid.core.netty.processor.filter.error;

import com.ruyuan.rapid.common.constants.ProcessorFilterConstants;
import com.ruyuan.rapid.common.enums.ResponseCode;
import com.ruyuan.rapid.common.exception.RapidBaseException;
import com.ruyuan.rapid.core.context.Context;
import com.ruyuan.rapid.core.context.RapidResponse;
import com.ruyuan.rapid.core.netty.processor.filter.AbstractEntryProcessorFilter;
import com.ruyuan.rapid.core.netty.processor.filter.Filter;
import com.ruyuan.rapid.core.netty.processor.filter.FilterConfig;
import com.ruyuan.rapid.core.netty.processor.filter.ProcessorFilterType;

/**
 * @author mac
 */
@Filter(
        id = ProcessorFilterConstants.DEFAULT_ERROR_FILTER_ID,
        name = ProcessorFilterConstants.DEFAULT_ERROR_FILTER_NAME,
        value = ProcessorFilterType.ERROR,
        order = ProcessorFilterConstants.DEFAULT_ERROR_FILTER_ORDER
)
public class DefaultErrorFilter extends AbstractEntryProcessorFilter<FilterConfig> {

    public DefaultErrorFilter() {
        super(FilterConfig.class);
    }

    /**
     * 真正执行过滤器的方法
     * @param ctx
     * @param args
     * @throws Throwable
     */
    @Override
    public void entry(Context ctx, Object... args) throws Throwable {
        try {
            Throwable throwable = ctx.getThrowable();
            ResponseCode responseCode = ResponseCode.INTERNAL_ERROR;
            if (throwable instanceof RapidBaseException) {
                RapidBaseException rapidBaseException = (RapidBaseException) throwable;
                responseCode = rapidBaseException.getCode();
            }
            RapidResponse rapidResponse = RapidResponse.buildRapidResponse(responseCode);
            ctx.setResponse(rapidResponse);
        } finally {
            System.out.println("====================== do error filter ======================");
            // 设置写回标记
            ctx.writtened();

            // 触发后面的过滤器执行
            super.fireNext(ctx, args);
        }
    }
}
